import 'package:flutter/material.dart';
import 'package:flutter_application_1/models/User.dart';
import 'package:flutter_application_1/provider/cart_provider.dart';

class UserProvider with ChangeNotifier {
  User? user;

  String token;

  CartProvider? cartProvider;

  UserProvider({
    this.user,
    this.token = '',
    this.cartProvider,
  });

  bool get isLogin {
    return false;
  }

  setToken(String data) {
    if (data.isEmpty) return;
    token = data;
    notifyListeners();
  }

  setUser(User data) {
    user = data;
    notifyListeners();
  }

  // 登录
  Future<dynamic> login(Map<String, dynamic> formData) async {
    await Future.delayed(Duration(seconds: 1));

    setToken('token_123456');

    cartProvider?.getCartList();

    await getUserInfo();
  }

  // 获取用户信息
  Future<dynamic> getUserInfo() async {
    if (token.isEmpty) return throw AssertionError('token 为空');

    await Future.delayed(Duration(seconds: 1));

    User user = User.fromJson({
      'id': '123456789',
      'username': 'fanzhiliang',
      'phone': '13128269543',
      'gender': 1
    });

    setUser(user);

    return user;
  }
}
